function A = plotPeakTiming(datatable, header, cfg)
%PLOTPEAKTIMING
if ~exist('cfg', 'var')
    cfg = plotPeakTiming_defaultCfg();
end

tfSig = [datatable{:,strcmp(header,'P')}]<0.025;
% tfB1 = [datatable{:,strcmp(header,'Latency (ms)')}]>-2000;
% tfB2 = [datatable{:,strcmp(header,'Latency (ms)')}]<2000;
% datatable = datatable(tfSig & tfB1 & tfB2,:);
datatable = datatable(tfSig,:);

% Get peaks for one channel & frequency
channels = unique(datatable(:,strcmp(header,'Channel')));
DRAWDATA = [];
for r = 1:length(channels)
    channel = channels{r};
    tfC = strcmp(datatable(:,strcmp(header,'Channel')),channel);
    tfB = strcmp(datatable(:,strcmp(header,'Bin')), cfg.binSelection);
    tf = tfC & tfB;
    subset = datatable(tf,:);
    for s = 1:size(subset,1)
        DRAWDATA(end+1).channelNo = r;
        DRAWDATA(end).x1 = subset{s,strcmp(header,'F30p Latency')};
        DRAWDATA(end).x2 = subset{s,strcmp(header,'Latency (ms)')};
        DRAWDATA(end).type = subset{s, strcmp(header,'Type')};
        DRAWDATA(end).channel = channels{r};
    end    
end

% Get the current axes
A = gca;

% Draw the gridlines
for s = 1:length(DRAWDATA);
    x1 = DRAWDATA(s).x1; x2 = DRAWDATA(s).x2;
    r = DRAWDATA(s).channelNo; channel = DRAWDATA(s).channel;
    L = line([x1 x1],[r 0], 'Color', [0.8 0.8 0.8], 'LineWidth', 0.5, 'LineStyle', '--', 'Parent', A);
    set(get(get(L,'Annotation'),'LegendInformation'), 'IconDisplayStyle', 'off');
end

% Draw the timing blocks
for s = 1:length(DRAWDATA);
    x1 = DRAWDATA(s).x1; x2 = DRAWDATA(s).x2;
    channel = DRAWDATA(s).channel;
    t = DRAWDATA(s).type;
%     p.FaceVertexCData = GetColor(coloring, channel)
    C = GetChannelConfig(cfg, channel);
    y = C.YLocation; 
    P = patch([x1 x1 x2 x2], [y-0.4 y+0.4 y+0.4 y-0.4], C.Color, 'Parent', A);
    text(x1-25, y, [channel ' ' t], 'Interpreter', 'none', ...
        'FontSize', 5, 'FontAngle', 'italic', 'FontWeight', 'bold', ...
        'HorizontalAlignment', 'right', 'Parent', A); % 'BackgroundColor', [.7 .9 .7],
    set(P, 'DisplayName', channel);
end

ylim([0.5 12.5]);
xlim([-2200 2200]);
set(gca, 'YTickLabel', {});

end

function C = GetChannelConfig(cfg, channel)
selectTf = strcmp({cfg.Channels.Label}, channel);
if ~any(selectTf)
    selectTf = strcmp({cfg.Channels.Label}, 'n/a');
end
C = cfg.Channels(find(selectTf,1,'first'));
% if size(C,1)>1
%     C = C';
% end
end